package com.woniuxy.java102vuecli.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.java102vuecli.controller.ResponseResult;
import com.woniuxy.java102vuecli.service.PermissionService;
import com.woniuxy.java102vuecli.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author author
 * @Create 2023-09-21 11:34
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("AuthorizationInterceptor");
        //对OPTIONS请求放行

        if(request.getMethod().equals("OPTIONS")){
            log.info("OPTIONS请求，放行");
            return true;
        }
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("token");
        //请求后端的路径   localhost:8080/employee/remove
        //如何做权限判断：根据用户查询对应的角色拥有的权限   ename=b rid=1 "/employee/get"
        log.info("request.getRequestURI()={}",request.getRequestURI());
        log.info("request.getRequestURL()={}",request.getRequestURL());
        List<String> permissionPaths= permissionService.getPermissionPathsByEid(Integer.parseInt(JwtUtil.getEid(token)));
        log.info("permissionPaths={}",permissionPaths);
        List<String> filterPaths = permissionPaths.stream().filter(path -> path!=null && request.getRequestURI().contains(path)).collect(Collectors.toList());
        log.info("AuthorizationInterceptor,filter过滤结果:{}",filterPaths);
        if(filterPaths.size()==0){
            log.info("AuthorizationInterceptor，没有权限，拦截");
            ResponseResult<String> responseResult=new ResponseResult<>(403,"error","没有权限");
            response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
            return false;
        }
        return true;

    }
}
